package Controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/patrickmn/go-cache"
	"net/http"
	"smartHomeNode/v1/base"
	"smartHomeNode/v1/config"
	"strconv"
	"time"
)

type ButtonController struct {
	BaseController
}

/**
 * 获取首页信息
 */
func (ctx *ButtonController) Index(c *gin.Context) {
	c.JSON(http.StatusOK, ctx.GoSuccess(ctx.GetButtonStatus(), ctx.GetDeviceAlias()))
}

/**
 * 控制方法
 */
func (ctx *ButtonController) Control(c *gin.Context) {
	json := make(map[string]interface{})
	c.BindJSON(&json)
	str := fmt.Sprintf("%v", json["data"])
	if ctx.RequestTCP(str) {
		name := ctx.Any2Str(json["name"])
		alias := ctx.Any2Str(json["alias"])
		if name != "" && alias != "" && name != alias {
			ctx.WriteFile(config.ALIASFILE + name, alias) // 文件存储别名
			base.DeviceAlias.Set(name, alias, cache.DefaultExpiration)
		}
		c.JSON(http.StatusOK, ctx.GoSuccess("", ""))
	} else {
		c.JSON(http.StatusOK, ctx.GoFail("", ""))
	}
}

/**
 * 延时控制方法
 */
func (ctx *ButtonController) Delay(c *gin.Context) {
	json := make(map[string]interface{})
	c.BindJSON(&json)
	delayTime := fmt.Sprintf("%v", json["delay"])
	startCol := fmt.Sprintf("CONTROL/:%v/:ON", json["name"])
	stopCol := fmt.Sprintf("CONTROL/:%v/:OFF", json["name"])
	if !ctx.RequestTCP(startCol) {
		c.JSON(http.StatusOK, ctx.GoFail("", ""))
		return
	}
	go func() {
		i, _ := strconv.ParseInt(delayTime, 10, 64)
		time.Sleep(time.Duration(i*60) * time.Second)
		if !ctx.RequestTCP(stopCol) {
			fmt.Println("Delay Control Error")
		}
	}()
	c.JSON(http.StatusOK, ctx.GoSuccess("", ""))
}

/**
 * 浏览器控制方法 http://server.com/api/button/control/TEST001/ON
 */
func (ctx *ButtonController) UrlControl(c *gin.Context) {
	name := c.Param("name")
	control := c.Param("control")
	if ctx.RequestTCP("CONTROL/:" + name + "/:" + control) {
		c.JSON(http.StatusOK, ctx.GoSuccess("", ""))
	} else {
		c.JSON(http.StatusOK, ctx.GoFail("", ""))
	}
}

/**
 * 浏览器控制方法 http://server.com/api/button/delay/TEST001/3
 */
func (ctx *ButtonController) UrlDelayControl(c *gin.Context) {
	delayTime := fmt.Sprintf("%v", c.Param("delay"))
	startCol := fmt.Sprintf("CONTROL/:%v/:ON", c.Param("name"))
	stopCol := fmt.Sprintf("CONTROL/:%v/:OFF", c.Param("name"))
	if !ctx.RequestTCP(startCol) {
		c.JSON(http.StatusOK, ctx.GoFail("", ""))
		return
	}
	go func() {
		i, _ := strconv.ParseInt(delayTime, 10, 64)
		time.Sleep(time.Duration(i*60) * time.Second)
		if !ctx.RequestTCP(stopCol) {
			fmt.Println("Delay Control Error")
		}
	}()
	c.JSON(http.StatusOK, ctx.GoSuccess("", ""))
}
